from django.shortcuts import render
from django.views import View
import json
from django import http
from django.db import DatabaseError
from message.models import Chat, RecentNews
from user.models import User
from essay.models import Essay, Like
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
user_dict = {}


# 用户聊天接口
class UserChat(WebsocketConsumer):

    def websocket_connect(self, message):
        print("创建")
        # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
        self.accept()
        user_id = self.scope.get("url_route").get("kwargs").get("user_id")
        user_dict[user_id] = self

    def websocket_receive(self, message):
        # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
        ws_data = json.loads(message['text'])
        from_user_id = ws_data['from_user_id']
        to_user_id = ws_data['to_user_id']
        chat_content = ws_data['chat_content']
        is_image = ws_data['is_image']
        is_show_time = ws_data['is_show_time']
        try:
            my_chat = Chat.objects.create(from_user_id=from_user_id, to_user_id=to_user_id, chat_content=chat_content,
                                          is_image=is_image, is_send=True, is_read=True, is_show_time=is_show_time)
            to_chat = Chat.objects.create(from_user_id=to_user_id, to_user_id=from_user_id, chat_content=chat_content,
                                          is_image=is_image, is_send=False, is_read=False, is_show_time=is_show_time)
        except DatabaseError:
            return http.JsonResponse({'code': '207', 'message': '发送失败'})
        recent_news_data_me = RecentNews.objects.values().filter(user_id=from_user_id, recent_user_id=to_user_id)
        recent_news_data_to = RecentNews.objects.values().filter(user_id=to_user_id, recent_user_id=from_user_id)
        if recent_news_data_me:
            RecentNews.objects.filter(user_id=from_user_id, recent_user_id=to_user_id).update(last_msg=('[图片]' if is_image else chat_content))
        else:
            RecentNews.objects.create(user_id=from_user_id, recent_user_id=to_user_id, last_msg=('[图片]' if is_image else chat_content))
        if recent_news_data_to:
            RecentNews.objects.filter(user_id=to_user_id, recent_user_id=from_user_id).update(
                last_msg=('[图片]' if is_image else chat_content))
        else:
            RecentNews.objects.create(user_id=to_user_id, recent_user_id=from_user_id,
                                      last_msg=('[图片]' if is_image else chat_content))
        ws_data['chat_id'] = my_chat.chat_id
        ws_data['to_chat_id'] = to_chat.chat_id
        ws_data['is_send'] = False
        ws_data['chat_time'] = my_chat.chat_time.strftime("%Y年%m月%d日 %H:%M")
        if str(ws_data['to_user_id']) in user_dict:
            ws1 = user_dict.get(str(ws_data['to_user_id']))
            ws1.send(json.dumps(ws_data))
        ws2 = user_dict.get(str(ws_data['from_user_id']))
        ws_data['is_send'] = True
        ws2.send(json.dumps(ws_data))

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        raise StopConsumer()


# 获取用户聊天记录
class GetUserChat(View):

    def post(self, request):
        from_user_id = json.loads(request.body)['from_user_id']
        to_user_id = json.loads(request.body)['to_user_id']
        try:
            Chat.objects.filter(from_user_id=from_user_id, to_user_id=to_user_id).update(is_read=True)
            chat_data = list(Chat.objects.values().filter(from_user_id=from_user_id, to_user_id=to_user_id))
            user_data = list(User.objects.values().filter(user_id=to_user_id))[0]
            for item in chat_data:
                item['chat_time'] = item["chat_time"].strftime("%Y年%m月%d日 %H:%M")
        except Exception:
            chat_data = []
            user_data = {}
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': {'chat_data': chat_data, 'user_data': user_data}})


# 撤销聊天接口
class CancelChat(View):

    def post(self, request):
        chat_id = json.loads(request.body)['chat_id']
        to_chat_id = json.loads(request.body)['to_chat_id']
        Chat.objects.filter(chat_id=chat_id).delete()
        Chat.objects.filter(chat_id=to_chat_id).delete()
        return http.JsonResponse({'code': '200', 'message': '撤销成功'})


# 删除聊天记录接口
class DeleteChat(View):

    def post(self, request):
        chat_id = json.loads(request.body)['chat_id']
        Chat.objects.filter(chat_id=chat_id).delete()
        return http.JsonResponse({'code': '200', 'message': '删除成功'})


# 获取近期聊天对象
class GetRecentChat(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        recent_data = list(RecentNews.objects.values().filter(user_id=user_id))
        for item in recent_data:
            user_data = list(User.objects.values().filter(user_id=item['recent_user_id']))[0]
            item['avatar'] = user_data['avatar']
            item['username'] = user_data['username']
            chat_data_count = Chat.objects.filter(from_user_id=user_id, to_user_id=item['recent_user_id'], is_read=False).count()
            item['unread_msg_count'] = chat_data_count
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': recent_data})


# 删除近期聊天对象
class DeleteRecentChat(View):

    def get(self, request):
        news_id = request.GET.get('news_id')
        try:
            RecentNews.objects.filter(news_id=news_id).delete()
        except DatabaseError:
            pass
        return http.JsonResponse({'code': '200', 'message': '删除成功'})


# 获取所有未读消息
class GetUnreadMsg(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        chat_data_count = Chat.objects.filter(from_user_id=user_id, is_read=False).count()
        recent_data = RecentNews.objects.values().filter(user_id=user_id)
        default_user_id = 0
        if recent_data:
            default_user_id = list(recent_data)[0]['recent_user_id']
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': {'unread_my_msg': chat_data_count, 'default_user_id': default_user_id}})


# 获取用户收到的赞
class GetUserLike(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        user_data = list(User.objects.values().filter(user_id=user_id))[0]
        essay_data = list(Essay.objects.values().filter(phone=user_data['phone']))
        result_data = []
        for item in essay_data:
            like_data = list(Like.objects.values().filter(essay_id=item['essay_id']))
            for like in like_data:
                like_user_data = list(User.objects.values().filter(phone=like['phone']))[0]
                result_data.append({
                    'avatar': like_user_data['avatar'],
                    'username': like_user_data['username'],
                    'like_time': like['like_time'].strftime("%Y年%m月%d日 %H:%M"),
                    'user_id': like_user_data['user_id'],
                    'essay_data': item
                })
        result_data.sort(key=lambda x: x['like_time'], reverse=True)
        return http.JsonResponse({'code': '200', 'message': '成功', 'data': result_data})
